/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Project2.cs342.project1.mathNotebook.Database;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Rick
 */
public class SQLConfigeration {
    static String db;
    static String pw;
    static String dbURL;
    static Connection conn;
    static Properties prop;
    static FileInputStream in;
    static boolean alreadyConnected;

    public SQLConfigeration(){
        alreadyConnected = false;
    }

    public static Connection getConnection(){
        if(alreadyConnected){
            System.out.println("Already Connected");
        }else{
            String propFile = "config.properties";
            try {
                //load properties file
                prop = new Properties();
                in = new FileInputStream(propFile);
                prop.load(in);

                db = prop.getProperty("db");
                pw = prop.getProperty("pw");
    //            System.out.println("Property Database: " + db +
    //                                "\nProperty Password: " + pw);

                //establish connection
                Class.forName("com.mysql.jdbc.Driver");
                dbURL = "jdbc:mysql://cs346.cs.uwosh.edu:4381/" + db;
                System.out.println("Attemping Connection");
                conn = DriverManager.getConnection(dbURL, db, pw);
                System.out.println("Connection Successful");
                alreadyConnected = true;
                //conn.close();
            }catch(IOException ex){
                System.out.println("Could not Load " + propFile);
            }catch(ClassNotFoundException ex){
                System.out.println("Error: " + ex);
            }catch(SQLException ex){
                System.out.println("Error: " + ex);
            }finally{
                try{
                    in.close();
                }catch(IOException ex){
                    System.out.println("Error: " + ex);
                }
            }
        }
        
        return conn;
    }

    public void closeConnection(){
        try {
            conn.close();
        } catch (SQLException ex) {
            System.out.println("Error " + ex);
        }
    }

}
